<template>
  <div>
    <!--搜索区域卡片-->
    <el-card class="box-card">
      <!--搜索表单-->
      <el-form :inline="true" ref="searchForm" :model="searchForm" class="demo-form-inline">
        <el-form-item label="用户名" prop="username">
          <el-input size="small" clearable v-model="searchForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input size="small" clearable v-model="searchForm.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select size="small" clearable style="width:100px" v-model="searchForm.sex" placeholder="性别">
            <el-option label="-" value=""></el-option>
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item  prop="date">
          <el-date-picker
              size="small"
              style="width:240px"
              v-model="searchForm.date"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <!--
            表单重置,需要
            1) form添加ref 引用名
            2) 每个表单项el-form-item 添加prop="属性">
            3) 事件触发,传入表单名
            4) 函数中调用固定方法 this.$refs[formName].resetFields();完成重置
          -->
          <el-button type="primary" size="small" @click="resetSearch('searchForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!--下方表格区域-->
    <el-card class="table-card">
      <!--批量删除按钮-->
      <el-button size="small" type="danger" @click="deleteBatch"> <i class="el-icon-delete"></i> 批量删除</el-button>

      <!--添加按钮-->
      <el-button size="small" type="success" @click="openDialog"><i class="el-icon-plus"></i> 添加</el-button>

      <el-table
          :data="tableData"
          @selection-change="handleSelectionChange"
          style="width: 100%"
      >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
        <el-table-column
            prop="id"
            width="80"
            label="编号">
        </el-table-column>
        <el-table-column
            prop="username"
            width="100"
            label="姓名">
        </el-table-column>
        <el-table-column
            prop="password"
            width="100"
            label="密码">
        </el-table-column>
        <el-table-column
            prop="avatar"
            label="头像">
          <template slot-scope="scope">
            <el-avatar shape="square" :size="50" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column
            prop="phone"
            label="手机号">
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="注册时间">
        </el-table-column>
        <el-table-column
            prop="money"
            width="130"
            label="余额">
        </el-table-column>
        <el-table-column
            prop="sex"
            width="80"
            label="性别">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageinfo.pageNum"
          :page-sizes="[3, 6, 10, 20]"
          :page-size="pageinfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageinfo.total">
      </el-pagination>

    </el-card>

    <!--添加/更新共用对话框-->
    <el-dialog :title="dialogTitle" :visible.sync="userDialogVisible" width="500px">
      <el-form  ref="userForm" :model="userForm" label-position="left" label-width="60px">
        <el-form-item label="用户名" prop="username">
          <el-input clearable v-model="userForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input clearable v-model="userForm.password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input  clearable v-model="userForm.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select  clearable style="width:100px" v-model="userForm.sex" placeholder="性别">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="余额" prop="money">
          <el-input clearable v-model="userForm.money" placeholder="余额"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="createTime">
          <el-date-picker
              v-model="userForm.createTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="handleForm">确定</el-button>
          <el-button type="primary"  @click="resetUserDialog('userForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {findUser, delBatch, addUser, updateUser} from '@/api/user'
export default {
  name: "UserView",
  data() {
    return {
      // 日期选项快捷组件
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 分页+搜索关键词
      searchForm: {
        username: '',
        phone: '',
        sex: null,
        date: [],
        beginDate:null,
        endDate:null,
        pageSize:3,
        pageNum:1
      },
      // 表格数据
      tableData:[],
      // 分页数据
      pageinfo:{
        pageSize:3,
        pageNum:1,
        total:null,
        pages: null
      },
      ids:[],
      dialogTitle:"添加",
      // 对话框的可见状态
      userDialogVisible:false,
      userForm:{}
    }
  },
  // 生命周期函数,会随着页面加载完毕,自动调用
  created() {
    this.fetchData();
  },
  methods: {
    // 获取用户数据
    fetchData(){
      // 发请求
      findUser(this.searchForm).then(res => {
        if (res.code !== 200) {
          this.$message.warning(res.msg)
          this.tableData = []
        } else {
          this.$message.success("查询用户成功")
          // res是R.data是pageVo
          this.tableData = res.data.list
          // 前端展示分页信息
          this.pageinfo.pageSize = res.data.pageSize
          this.pageinfo.pageTotal = res.data.pageTotal
          this.pageinfo.total = res.data.total
          this.pageinfo.pages = res.data.pages
        }
      })
    },
    // 搜索
    onSearch() {
      this.searchForm.beginDate = this.searchForm.date[0]
      this.searchForm.endDate = this.searchForm.date[1]
      console.log("搜索关键词2", this.searchForm)
      this.fetchData();
    },
    // 复选框改变
    handleSelectionChange(row) {
      // console.log("勾选的行",row)
      this.ids = []
      // 组装勾选的行 id数组 , map类似于java的stream流中的map
      row.map(item =>{
        this.ids.push(item.id)
      })
      console.log("勾选的行id",this.ids)
    },
    // 处理更新
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogTitle = "更新"
      this.userDialogVisible = true
      this.userForm = { ...row }
    },
    // 处理删除
    handleDelete(index, row) {
      console.log(index, row);

    },
    // 重置搜索表单
    resetSearch(formName){
      this.$refs[formName].resetFields();
      this.fetchData()
    },
    // 页面大小改变触发
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.pageSize = val;
      this.fetchData()
    },
    // 当前页改变(跳转)
    handleCurrentChange(val) {
      console.log(`第 ${val} 页`);
      this.searchForm.pageNum = val
      this.fetchData()
    },
    // 批量删除
    deleteBatch(){
      if (!this.ids.length){
        this.$message.error("没有选择任何数据删除!")
        return
      }
      this.$confirm('是否确认删除数据编号为['+this.ids+']的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发请求删除
        // this.ids.join(",");// [1,2,3] ==> "1,2,3"
        // 将id数组拼接成字符串
        delBatch({ids:this.ids.join(",")}).then(res=>{
          // console.log("删除返回",res)
          if (res.code != 200) {
            this.$message.error("删除失败")
          } else {
            this.$message.success("删除成功")
            this.searchForm.pageNum = 1;
            this.fetchData()
          }
        })
      }).catch(() => {
        this.$message.info("取消删除  ")
      });
    },
    // 打开添加对话框
    openDialog(){
      this.dialogTitle = "添加"
      this.userDialogVisible = true
    },
    // 执行添加/更新逻辑
    handleForm(){
      if(this.dialogTitle == "添加"){
        // console.log("添加",this.userForm)
        addUser(this.userForm).then(res => {
          if (res.code != 200){
            this.$message.error("添加失败")
          } else {

            this.$message.success("添加成功")
            this.searchForm.pageNum = 1;
            this.fetchData()
          }
          // 关闭对话
          this.userDialogVisible = false
        })
      } else  {
        if (this.dialogTitle == "更新"){
          updateUser(this.userForm).then(res => {
            if (res.code != 200){
              this.$message.error("更新失败")
            } else {
              this.$message.success("更新成功")
              this.searchForm.pageNum = 1;
              this.fetchData()
            }
            // 关闭对话
            this.userDialogVisible = false
          })
        }
      }
    },
    // 重置添加/更新框
    // 重置搜索表单
    resetUserDialog(formName){
      this.$refs[formName].resetFields();
    },
  }
}
</script>

<style scoped>
.box-card {
  width: 100%;
  height: 70px;
  border-radius: 10px;
  margin-bottom: 10px;
}
.table-card{
  border-radius: 10px;
}
</style>
